<template>
  <div class="ft-user-select" style="text-align: left">
    <el-select :disabled="disabled" v-if="editable" v-model="user" value-key="userId" :placeholder="placeholder"
               @change="selectUser" filterable :filter-method="loadUserList" :clearable="clearable"
               :popper-append-to-body="popperAppendToBody">
      <el-option
        v-for="item in userList"
        :key="item.userId"
        :label="item.userName + ' | '+ item.deptName"
        :value="item">
      </el-option>
    </el-select>
    <span v-if="!editable&&user">{{user.userName}}</span>
  </div>
</template>

<script>
  export default {
    name: "FtTransferUser",
    props: {
      placeholder: {
        type: String,
        default: '请选择用户'
      },
      value: {
        type: String
      },
      editable: {
        type: Boolean,
        default: true
      },
      disabled: {
        type: Boolean,
        default: false
      },
      clearable: {
        type: Boolean,
        default: false
      },
      popperAppendToBody: {
        type: Boolean,
        default: true
      }
    },
    mounted() {
      this.loadUserList()
      this.loadUser()
    },
    data() {
      return {
        userList: [],
        user: null,
        userId: this.value,
        deptId: {type: String}
      }
    },
    methods: {
      loadUser() {
        this.user = null
        if (this.userId) {
          const url = '/joys-rest/lss-customer/transfer/user/' + this.userId
          this.$http.get(url).then(resp => {
            this.user = resp.body
            this.merge()
          }, resp => {
            this.$message.error(resp.body.message)
          })
        }
      },
      loadUserList(filter) {
        const url = '/joys-rest/lss-customer/transfer/user/query/'
        this.$http.post(url, filter, {
          headers: {'Content-Type': 'text/plain'}
        }).then(resp => {
            this.userList = resp.body
            this.merge()
          }, resp => {
            this.$message.error(resp.body.message)
          }
        )
      },
      selectUser() {
        this.userId = this.user.userId
        this.deptId = this.user.deptId
        this.$emit('change', this.user)
        this.$emit('input', this.userId)
      },
      merge() {
        this.$emit('load',this.user)
        const found = this.userList && this.userList.find(user => {
          return user.userId == this.userId
        })
        if (!found && this.user) {
          this.userList = (this.userList || [])
          this.userList.push(this.user)
        }
      }
    },
    watch: {
      value(newVal) {
        this.userId = newVal
        this.loadUser()
      }
    }
  }
</script>

<style>
  .ft-user-select {
    display: inline-block;
    text-align: left;
  }

  .ft-user-select .el-select {
    width: 100%;
  }
</style>
